<?php
class Login {
    private  $db;
	public function Login() {
	    $this->db=Options::getDb();
	}
	public function verificaLogin($tarefas =false,$noRedirect=false ) {
		if($noRedirect ==true){
			return true;
		}
		if (empty ( $_SESSION ["usuario"] ) ) {
			$this->redirect ( "/login" );
		} else if($tarefas ==false){
			$this->redirect ( "/tarefas" );
		}
	}
	public function redirect($page) {
		if (! isset ( $page )) {
			$page = "/";
		}
		header ( 'Location: ' . $page );
	}
	
	public function logOut(){
		session_destroy();
		$this->redirect( "/login"  );
	}
	
	
	public function logar($usr, $pass) {
		$error="";
		try {
			$Conexao = Conexao::Conect();
			$sql="SELECT nome,id
					FROM {$this->db}.usuario 
					WHERE 
					  nome = " . $Conexao->quote ( $usr ). 
					"AND  senha =  '" . sha1( $pass )."';";
			$data = $Conexao->query ( $sql );
			if ( $data->rowCount() > 0) {
				$row = $data->fetch();
				$Usuario = new Usuario();
				$Usuario->setId($row["id"]);
				$Usuario->setNome($row["nome"]);
				$_SESSION["usuario"]=serialize($Usuario);
				$this->insere($row["id"]);
				header('Location: /tarefas');
				exit;
			}
			else{
				$error="Login ou senha invalida";
			}
			return $error;	
			
		} catch ( PDOException $e ) {
			echo 'ERROR: ' . $e->getMessage ();
			return $error;
		}
	}
	
	public function insere($id){
		try {
			$Conexao = Conexao::Conect();
			$sql="INSERT INTO `{$this->db}`.`login` (
					`id` ,
					`usuario` ,
					`data`
					)
					VALUES (
						NULL , '".$id."', NOW()
					);";
			$data = $Conexao->query ( $sql );
			//echo $data->rowCount(); // 1
		} catch ( PDOException $e ) {
			echo 'ERROR: ' . $e->getMessage ();
		}
	}
}